import * as netdiskService from '../services/netdisk';

export default {
  namespace: 'netdisk',
  state: {
    list: [],
    tree: {id: -1, name: '/', type: 'dir', children: []},
    content: {},
    pwd: '/',

  },
  reducers: {
    save(state, { payload: { data} }) {
      return { ...state, list: data.result};
    },
    changeDir(state, { payload: { path }}) {
      return { ...state, pwd: path}
    }
  },
  effects: {
    *list({ payload: { action='list', path='/' } }, { call, put }) {
      const { data, headers } = yield call(netdiskService.list, { action, path });
      yield put({
        type: 'save',
        payload: {
          data
        },
      });
      yield put({
        type: 'changeDir',
        payload: {
          path
        }
      })
    },
    *create({ payload: values }, { call, put }) {
      yield call(netdiskService.create, values);
      yield put({ type: 'reload' });
    },
    *reload(action, { put, select }) {
      const page = yield select(state => state.netdisk.page);
      yield put({ type: 'fetch', payload: { page } });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/netdisk') {
          dispatch({ type: 'list', payload: query });
        }
      });
    },
  },
};
